package com.suxin.http.response.handler;

import com.alibaba.cloud.commons.io.IOUtils;
import com.suxin.http.model.HttpRestResult;
import com.suxin.http.response.HttpClientResponse;
import org.apache.http.HttpStatus;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * @author Tang
 * @classname AbstractResponseHandler
 * @description [ 抽象响应处理类，，具体子类处理 ]
 * @date 2023/3/2 19:00
 */
public abstract class AbstractResponseHandler<T> implements ResponseHandler<T>{

    private Type type;

    @Override
    public void setResponseType(Type type) {
        this.type = type;
    }

    @Override
    public HttpRestResult<T> handlerResponse(HttpClientResponse response) throws IOException {
        if (response.getStatusCode() != HttpStatus.SC_OK) {
            return handlerError(response);
        }
        return convertHandler(response,this.type);
    }

    /**
     * convertHandler
     * @param response
     * @param type
     * @return
     */
    protected abstract HttpRestResult<T> convertHandler(HttpClientResponse response,
                                                    Type type) throws IOException;

    /**
     * 处理 error
     * @param response
     * @return
     * @throws IOException
     */
    private HttpRestResult<T> handlerError(HttpClientResponse response) throws IOException{
        final String body = IOUtils.toString(response.getBody(), Charset.defaultCharset());
        return new HttpRestResult<T>(response.getStatusCode(), body, null,response.getHeaders());
    }

}
